package cn.iocoder.yudao.module.trade.job.orderpostback;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.trade.controller.admin.orderpostback.vo.OrderPostBackPageReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.orderpostback.OrderPostBackDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.orderpostconfig.OrderPostConfigDO;
import cn.iocoder.yudao.module.trade.enums.orderpostback.TradeOrderPostBackStatusEnum;
import cn.iocoder.yudao.module.trade.service.drainage.AbstractDrainageService;
import cn.iocoder.yudao.module.trade.service.drainage.DrainageService;
import cn.iocoder.yudao.module.trade.service.drainage.DrainageServiceFactory;
import cn.iocoder.yudao.module.trade.service.orderpostback.OrderPostBackService;
import cn.iocoder.yudao.module.trade.service.orderpostconfig.OrderPostConfigService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class OrderPostBackJob implements JobHandler {

    @Resource
    private OrderPostBackService orderPostBackService;
    @Resource
    private DrainageServiceFactory drainageServiceFactory;
    @Resource
    private OrderPostConfigService orderPostConfigService;

    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        int pageNo = 1;
        int pageSize = 1000;
        OrderPostBackPageReqVO reqVO = new OrderPostBackPageReqVO();
        reqVO.setPageNo(pageNo);
        reqVO.setPageSize(pageSize);
        reqVO.setStatus(TradeOrderPostBackStatusEnum.FAILED.getStatus());
        PageResult<OrderPostBackDO> pageResult = orderPostBackService.getOrderPostBackPage(reqVO);
        long total = pageResult.getTotal();
        if (CollectionUtil.isNotEmpty(pageResult.getList())) {
            for (OrderPostBackDO postBackDO : pageResult.getList()) {
                DrainageService drainageService = drainageServiceFactory.getByDrainageType(postBackDO.getThirdType());
                drainageService.processOrder(postBackDO);
            }
        }
        return String.format("处理订单回传数量: %d", total);
    }
}
